package com.lwbldy.common.tools;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.multipart.MultipartFile;

public class FileUtils {

    public static String saveFile(MultipartFile file,String rootPath,String idCard){
        // 获取文件后缀
        String prefix="."+getExtensionName(file.getOriginalFilename());
        String fileName = idCard+prefix;
        java.io.File filepath = new java.io.File(rootPath, fileName);

        if (!filepath.getParentFile().exists()) {
            filepath.getParentFile().mkdirs();
        }

        try{
            Thumbnails.of(file.getInputStream())
                    .scale(1f)
                    .outputQuality(0.5f)
                    .toFile(filepath);
            return fileName;
        }catch (Exception e){

            return null;
        }
    }

    /**
     * 获取文件扩展名，不带 .
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot >-1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }


}
